import {
  deepCopyObj,
  deepCopyObjArray
} from '../../../../assets/js/help';

export default {
  data() {
    var checkMoney = (rule, value, callback) => {
      if (value === 0 || value === "0") {
        return callback();
      }
      if (!value || value == "" || value == null) {
        callback();
      } else if (!/^\d+(\.\d+)?$/.test(value)) {
        callback(new Error("请输入正确的金额"));
      } else if (value > this.SellCouponsModalData.mainData.totalMoney) {
        callback(new Error("商家折扣价不得大于总价"));
      } else {
        callback();
      }
    };
    var checkNumber = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入购买数量"));
      } else if (!/^[1-9]+[0-9]*$/.test(value)) {
        callback(new Error("请输入大于0的数量"));
      } else if (value > 100000) {
        callback(new Error("单次最多购买10万张"));
      } else if (this.SellCouponsModalData.mainData.maxBuyNum > 0 && value > this.SellCouponsModalData.mainData.maxBuyNum) {
        callback(new Error("购买数量超出限制数量"));
      } else if (this.SellCouponsModalData.mainData.totalAvilableToBuy > 0 && value > this.SellCouponsModalData.mainData.totalAvilableToBuy) {
        callback(new Error("购买数量超出剩余数量"));
      } else {
        callback();
      }
    };
    return {
      // 销售优惠券参数
      SellCouponsModalData: {
        couponName: '',
        select_list: [],
        mainData: {
          couponTmpId: "",
          coupon: "",
          realPrice: "",
          originalPrice: "",
          traderName: "",
          traderId: "",
          totalAvilableToBuy: "",
          maxBuyNum: "",
          sellNum: "",
          totalMoney: "",
          sellMoney: "",
          sellRemark: ""
        }
      },
      mainDatarules: {
        traderName: [{
          required: true,
          message: '请选择商户名称',
          trigger: 'change'
        }],
        sellMoney: [{
          validator: checkMoney,
          trigger: "change"
        }],
        sellNum: [{
          required: true,
          validator: checkNumber,
          trigger: "change"
        }]
      },
      SelectMerchantsModalData: {
        fixedCols: 3,
        tHeightModal: 300,
        list_data: {},
        pageNumber: 1,
        pageSize: 10,
        total: 0,
        theadsInfo: [{
            index: 1,
            prop: "name",
            label: "商家名称",
            minWidth: 100,
          },
          {
            index: 2,
            prop: "contact",
            label: "联系人",
            minWidth: 100,
          },
          {
            index: 3,
            prop: "tel",
            label: "联系电话",
            minWidth: 100,
          },
          {
            index: 4,
            prop: "isLimitBuy",
            label: "是否限购",
          },
          {
            index: 5,
            prop: "maxBuyNum",
            label: "限制购买数",
          },
        ],
        tbodysInfo: []
      },
      SelectMerchantsModalDataForm: {
        name: ""
      },
      isSingleCoupon: '', //是否售卖单个优惠券
      //销售优惠券弹框的选择框里当前选择的优惠券
      currentCouponObj: {},
      SellCouponsModalData_detial: {
        type: "add",
        id: null,
        name: "",
        areaName: "",
        CouponList: [],
        inputParks: [],
        balanceType: "0",
        sellFromTo: "",
        validFromTo: "",
        validDay: "",
        couponType: "0",
        faceValue: "",
        originalPrice: "",
        realPrice: "",
        useRuleMin: "",
        useRuleMax: "",
        totalNum: "",
        remark: "",
        isLimitTotal: "0",
        couponRule: "0",
        useParkingFee: "0"
      },
      parkIdsOfCoupon: '', //优惠配置-售卖优惠券-某张券适用的停车场数字id集合
    }
  },
  methods: {
    // 优惠券下拉框搜索失去焦点
    couponBlurEvent() {
      this.SellCouponsModalData.placeholderStr = '请选择'
    },
    // 优惠券下拉框搜索获得焦点
    couponFocusEvent() {
      this.SellCouponsModalData.placeholderStr = '请选择/搜索优惠券/停车场'
    },
    // 所有优惠券
    allCoupon(val) {
      let self = this
      self.SellCouponsModalData.select_list.forEach(elem => {
        elem.isHidden = false
      })
      self.SellCouponsModalData.select_list.push({})
      this.$nextTick(() => {
        self.SellCouponsModalData.select_list.pop()
      })
    },
    // 搜索优惠券
    searchCoupon(val) {
      let self = this
      self.SellCouponsModalData.select_list.forEach(elem => {
        elem.isHidden = true
        if (!val || elem.label.indexOf(val) > -1) {
          elem.isHidden = false
        }
      })
      self.SellCouponsModalData.select_list.push({})
      this.$nextTick(() => {
        self.SellCouponsModalData.select_list.pop()
      })
    },
    Coupon_change() {
      let _this = this;
      let index = _this.SellCouponsModalData.mainData.coupon;
      let data_source = _this.SellCouponsModalData.select_list[index];
      _this.currentCouponObj = deepCopyObj(_this.SellCouponsModalData.select_list[index]);
      _this.SellCouponsModalData.couponName = data_source.name
      _this.SellCouponsModalData.mainData.couponTmpId = data_source.tmpId;
      _this.SellCouponsModalData.mainData.realPrice = data_source.realPrice;
      _this.SellCouponsModalData.mainData.originalPrice = data_source.originalPrice;
      _this.SellCouponsModalData.mainData.totalAvilableToBuy = !(Number(data_source.totalAvilableToBuy) == -1) ? data_source.totalAvilableToBuy : "无限";
      _this.SellCouponsModalData.mainData.maxBuyNum = data_source.maxBuyNum ? data_source.maxBuyNum : (!(Number(data_source.totalAvilableToBuy) == -1) ? data_source.totalAvilableToBuy : "无限");
    },
    // 查看优惠券信息
    async check_sellCoupon_detail(initData){
      let _this = this
      let parkList = [] //选择的停车场
      let selectedMerchant = [] //可线上购买的商家
      var couponTypeId = function () {
        switch (initData.couponType) {
          case "免费券":
            return '0'
          case "金额扣减券":
            return '1'
          case "金额折扣券":
            return '2'
          case "金额固定值券":
            return '3'
          case "时间券":
            return '4'
          case "不同计价券":
            return '5'
          default:
            return null;
        }
      }();
      var couponRuleStr = function () {
        switch (initData.couponRule) {
          case 0:
            return '扣减前面时间'
          case 1:
            return '扣减后面时间'
          case 2:
            return '扣减进场时间和优惠时间计算的金额'
          case 3:
            return '扣减优惠时间和计费结束时间计算的金额'
          default:
            return null;
        }
      }();
      _this.SellCouponsModalData_detial = {
        id: null,
        name: initData.name, //优惠券名称
        parkNameListStr: '', //适用停车场
        balanceType: initData.balanceType, //销售结算
        sellFromTo: initData.sellFrom + ' 至 ' + initData.sellTo, //可售卖时间
        validFromTo: initData.validFrom + ' 至 ' + initData.validTo, //可发放时间
        validDay: initData.validDay, //使用有效期
        expireRefund: initData.expireRefund, //是否逾期退回
        couponTypeId: couponTypeId, // 券类型id
        couponTypeStr: initData.couponType, //券类型str
        couponRuleId: initData.couponRule, //扣减类型id
        couponRuleStr: couponRuleStr, //扣减类型str
        faceValue: initData.faceValue,
        originalPrice: initData.originalPrice, //优惠券原价
        realPrice: initData.realPrice, //折扣价
        useRule: initData.useRule.split('~')[0] + '元 - ' + initData.useRule.split('~')[1] + '元', //使用条件
        totalNum: initData.totalNum ? initData.totalNum + '张' : '', //券总数
        isLimitTotal: initData.totalNum ? 0 : 1, //券数量是否有限(0:有限;1:无限)
        useParkingFee: initData.useParkingFee ? initData.useParkingFee : null, //享受免费时长(1:享受;0:不享受)
        financialParkIdStr: '', //财务主体str
        couponListStr: '', //可线上购买券的商户str
        isCover: initData.isCover, //是否可叠加(0:否;1:是)
        isCoverStr: initData.isCover ? '是' : '否',
        maxCoverNum: initData.maxCoverNum, //一次停车最多使用张数
        useParkingFee: initData.useParkingFee ? '享受' : '不享受', //是否享受免费时长
      };

      let aparams = {
        couponTmpId: initData.couponTmpId
      }
      let bparams = {
        couponId: initData.id,
        sort: true
      }
      const [parkListRes, merchantListRes] = await Promise.all([
        API.fetchGet('/coupon/couponParkList.do', aparams),
        API.fetchGet('/coupon/getTrader2Sell.do', bparams)
      ])

      if(Array.isArray(parkListRes.data) && parkListRes.data.length){
        parkListRes.data.forEach(elem=>{
          if(elem.id==initData.financialParkId){ //财务主体
            _this.SellCouponsModalData_detial.financialParkIdStr = elem.name
          }
          parkList.push(elem.name) //适用的停车场
        })
        _this.SellCouponsModalData_detial.parkNameListStr = parkList.join(' / ')
      }

      if (Array.isArray(merchantListRes.data)) {
        merchantListRes.data.forEach(element => {
          if (element.checked) {
            selectedMerchant.push(element.name) //可线上购买的商家
          }
        })
        _this.SellCouponsModalData_detial.couponListStr = selectedMerchant.join(' / ')
      }
      _this.toOpenModal('SellCouponsModal_detail');
    },
    // 查看优惠券详情
    async SellCouponsModal_detail_open() {
      let _this = this;
      if (!_this.currentCouponObj) {
        _this.showToast('请先选择一个优惠券', 0, 2000);
        return;
      }
      let aparams = {
        id: _this.currentCouponObj.id
      }
      let bparams = {
        couponId: _this.currentCouponObj.id,
        sort: true
      }
      const [couponObjRes, merchantListRes] = await Promise.all([
        API.fetchGet('/coupon/detail.do', aparams),
        API.fetchGet('/coupon/getTrader2Sell.do', bparams)
      ])
      let initData = couponObjRes.data
      let selectedMerchant = []
      if (Array.isArray(merchantListRes.data)) {
        merchantListRes.data.forEach(element => {
          if (element.checked) {
            selectedMerchant.push(element.name)
          }
        })
      }
      var couponTypeId = function () {
        switch (initData.couponType) {
          case "免费券":
            return '0'
          case "金额扣减券":
            return '1'
          case "金额折扣券":
            return '2'
          case "金额固定值券":
            return '3'
          case "时间券":
            return '4'
          case "不同计价券":
            return '5'
          default:
            return null;
        }
      }();
      var couponRuleStr = function () {
        switch (initData.couponRule) {
          case 0:
            return '扣减前面时间'
          case 1:
            return '扣减后面时间'
          case 2:
            return '扣减进场时间和优惠时间计算的金额'
          case 3:
            return '扣减优惠时间和计费结束时间计算的金额'
          default:
            return null;
        }
      }();
      _this.SellCouponsModalData_detial = {
        id: null,
        name: initData.name, //优惠券名称
        parkNameListStr: _this.currentCouponObj.parkNameListStr, //适用停车场
        balanceType: initData.balanceType, //销售结算
        sellFromTo: initData.sellFrom + ' 至 ' + initData.sellTo, //可售卖时间
        validFromTo: initData.validFrom + ' 至 ' + initData.validTo, //可发放时间
        validDay: initData.validDay, //使用有效期
        expireRefund: initData.expireRefund, //是否逾期退回
        couponTypeId: couponTypeId, // 券类型id
        couponTypeStr: initData.couponType, //券类型str
        couponRuleId: initData.couponRule, //扣减类型id
        couponRuleStr: couponRuleStr, //扣减类型str
        faceValue: initData.faceValue,
        originalPrice: initData.originalPrice, //优惠券原价
        realPrice: initData.realPrice, //折扣价
        useRule: initData.useRule.split('~')[0] + '元 - ' + initData.useRule.split('~')[1] + '元', //使用条件
        totalNum: initData.totalNum ? initData.totalNum + '张' : '', //券总数
        isLimitTotal: initData.totalNum ? 0 : 1, //券数量是否有限(0:有限;1:无限)
        useParkingFee: initData.useParkingFee ? initData.useParkingFee : null, //享受免费时长(1:享受;0:不享受)
        financialParkIdStr: '', //财务主体str
        couponListStr: selectedMerchant.join(' / '), //可线上购买券的商户str
        isCover: initData.isCover, //是否可叠加(0:否;1:是)
        isCoverStr: initData.isCover ? '是' : '否',
        maxCoverNum: initData.maxCoverNum, //一次停车最多使用张数
        useParkingFee: initData.useParkingFee ? '享受' : '不享受', //是否享受免费时长
      };
      // 财务主体
      if (Array.isArray(_this.currentCouponObj.parkIdList)) {
        _this.currentCouponObj.parkIdList.forEach((element, index) => {
          if (element == initData.financialParkId) {
            _this.SellCouponsModalData_detial.financialParkIdStr = _this.currentCouponObj.parkNameList[index]
          }
        })
      }
      _this.toOpenModal('SellCouponsModal_detail');
    },
    // 打开销售优惠券框-商家管理
    SellCouponsModal_open2(rowData) {
      var _this = this;
      _this.isSingleCoupon = false
      _this.SellCouponsModalData = {
        placeholderStr: '请选择',
        couponName: '优惠券名称',
        select_list: [],
        mainData: {
          coupon: '',
          realPrice: '',
          originalPrice: '',
          traderName: rowData.name,
          traderId: rowData.id,
          totalAvilableToBuy: '',
          maxBuyNum: '',
          sellNum: '',
          totalMoney: '',
          sellMoney: '',
          sellRemark: '',
        }
      };
      let params = {}
      if(rowData.parkLongId){
        params.parkIds = rowData.parkLongId
      }
      // 获取优惠券名称
      API.fetchGet('/coupon/sell/getCouponList2.do',params)
        .then(res => {
          _this.SellCouponsModalData.select_list = []
          if (res.data.rows.length > 0) {
            _this.SellCouponsModalData.select_list = deepCopyObjArray(res.data.rows);
            _this.SellCouponsModalData.select_list.forEach(elem => {
              if (elem.parkNameList && Array.isArray(elem.parkNameList)) {
                elem.parkNameListStr = elem.parkNameList.join(' / ')
              } else {
                elem.parkNameListStr = ''
              }
              elem.label = elem.name + "-" + elem.parkNameListStr
              elem.isHidden = false
            });
            _this.toOpenModal('SellCouponsModal');
          } else {
            // icon: 0:普通提示 1：正确的提示 2： 错误提示
            // time: 不填默认1000ms
            _this.showToast('没有可销售的优惠券', 0, 2000);
          }
        }, err => {})
    },
    // 打开销售优惠券框
    SellCouponsModal_open(obj,params) {
      var _this = this;
      _this.isSingleCoupon = true
      _this.parkIdsOfCoupon = params ? params : ''
      _this.SellCouponsModalData = {
        couponName: '',
        select_list: [],
        mainData: {
          coupon: '',
          realPrice: '',
          originalPrice: '',
          traderName: '',
          traderId: '',
          totalAvilableToBuy: '',
          maxBuyNum: '',
          sellNum: '',
          totalMoney: '',
          sellMoney: '',
          sellRemark: '',
        }
      };
      _this.SellCouponsModalData.couponName = obj.name
      _this.SellCouponsModalData.mainData.coupon = 0
      _this.SellCouponsModalData.mainData.couponTmpId = obj.id;
      _this.SellCouponsModalData.mainData.realPrice = obj.realPrice;
      _this.SellCouponsModalData.mainData.originalPrice = obj.originalPrice;
      _this.SellCouponsModalData.mainData.totalAvilableToBuy = obj.totalNum - obj.totalAvilableToBuy; //剩余数量
      _this.SellCouponsModalData.mainData.maxBuyNum = obj.totalNum; //最大购买数量
      _this.toOpenModal('SellCouponsModal')
    },
    // 获取供选择用户的列表
    getTraderListModal_open() {
      let _this = this;
      let params = {
        query_parkId: _this.parkIdsOfCoupon,
        page: _this.SelectMerchantsModalData.pageNumber,
        rp: _this.SelectMerchantsModalData.pageSize
      }
      API.fetchGet('/coupon/sell/getTraderListByPage.do', params)
        .then(res => {
          _this.SelectMerchantsModalData.tbodysInfo = []
          if (res.data.rows.length > 0) {
            _this.SelectMerchantsModalData.tbodysInfo = res.data.rows;
            _this.SelectMerchantsModalData.total = res.data.total;
            _this.SelectMerchantsModalData.pageNumber = res.data.page;
            _this.toOpenModal('SelectMerchantsModal');
          } else {
            // icon: 0:普通提示 1：正确的提示 2： 错误提示
            // time: 不填默认1000ms
            _this.showToast('没有已启用的商户', 0, 2000);
          }
        }, err => {})
    },
    // 点击选择按钮时候执行
    handleEdit(index, row) {
      this.SellCouponsModalData.mainData.traderName = row.name;
      this.SellCouponsModalData.mainData.traderId = row.id;
      this.closed('SelectMerchantsModal');
    },
    // 弹框搜索项
    SelectMerchantsModalData_change() {
      var _this = this;
      _this.SelectMerchantsModalData.pageNumber = 1;
      var params = {
        page: _this.SelectMerchantsModalData.pageNumber,
        rp: _this.SelectMerchantsModalData.pageSize,
        name: _this.SelectMerchantsModalDataForm.name,
        query_parkId: _this.parkIdsOfCoupon
      }
      API.fetchGet('/coupon/sell/getTraderListByPage.do', params)
        .then(res => {
          _this.SelectMerchantsModalData.tbodysInfo = res.data.rows;
          _this.SelectMerchantsModalData.total = res.data.total;
          _this.SelectMerchantsModalData.pageNumber = res.data.page;
        }, err => {})
    },
    //保存售卖优惠券
    SellCouponsModal_save() {
      var _this = this;
      var _params = _this.SellCouponsModalData.mainData;
      if (!_params.traderName) {
        _this.showToast('请先选择商家', 0, 2000);
      }
      if (_params.sellMoney !== 0 && _params.sellMoney !== '0' && !_params.sellMoney) {
        _params.sellMoney = _params.totalMoney
      }
      _this.$refs['SellCoupons_form'].validate((valid) => {
        if (valid) {
          API.fetchPost('/coupon/sell/add.do', _params)
            .then(res => {
              if (res.status == 1) {
                _this.showToast(res.message, 1, 2000);
                _this.closed('SellCouponsModal');
                _this.getItemList();
              } else {
                _this.showToast('保存失败', 1, 2000);
              }
            }, err => {})
        }
      })
    },
    // 调用父组件的getItemList方法
    getItemList() {
      this.$emit('getItemList')
    },
    getReportDetailPagination(curPage, pageSize) {
      var _this = this;
      _this.SelectMerchantsModalData.pageNumber = curPage;
      _this.SelectMerchantsModalData.pageSize = pageSize ? pageSize : this.SelectMerchantsModalData.pageSize;
      var params = {
        page: _this.SelectMerchantsModalData.pageNumber,
        rp: _this.SelectMerchantsModalData.pageSize,
        query_parkId: _this.parkIdsOfCoupon
      }
      API.fetchGet('/coupon/sell/getTraderListByPage.do', params)
        .then(res => {
          if (res.data.rows.length > 0) {
            _this.SelectMerchantsModalData.tbodysInfo = res.data.rows;
            _this.SelectMerchantsModalData.total = res.data.total;
            _this.SelectMerchantsModalData.pageNumber = res.data.page;
          } else {
            // icon: 0:普通提示 1：正确的提示 2： 错误提示
            // time: 不填默认1000ms
            _this.showToast('没有可销售的优惠券', 0, 2000);
          }
        }, err => {})
    },
    prevPage() {
      this.SelectMerchantsModalData.pageNumber = this.SelectMerchantsModalData.pageNumber > 1 ? this.SelectMerchantsModalData.pageNumber - 1 : 1
    },
    nextPage() {
      this.SelectMerchantsModalData.pageNumber = this.SelectMerchantsModalData.pageNumber < this.SelectMerchantsModalData.total ? this.SelectMerchantsModalData.pageNumber + 1 : this.SelectMerchantsModalData.total
    },
  },
  computed: {
    pay: function () {
      if (this.SellCouponsModalData.mainData.sellNum > 0) {
        this.SellCouponsModalData.mainData.totalMoney = this.SellCouponsModalData.mainData.sellNum * this.SellCouponsModalData.mainData.realPrice;
        this.SellCouponsModalData.mainData.sellMoney = this.SellCouponsModalData.mainData.totalMoney;
        return this.SellCouponsModalData.mainData.totalMoney;
      } else {
        return '';
      }
    }
  },
}